package com.spddr.pmos.cxf.impl;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Service;

import com.spddr.pmos.cxf.JaxrsReservoirLevelVolume;
import com.spddr.pmos.jpa.ReservoirLevelVolume;
import com.spddr.pmos.jpa.ReservoirLevelVolumeId;
import com.spddr.pmos.repos.ReservoirLevelVolumeRepos;

import cn.seqdata.echarts.Option;
import cn.seqdata.echarts.axis.CategoryAxis;
import cn.seqdata.echarts.axis.ValueAxis;
import cn.seqdata.echarts.series.Line;

@Service
public class JaxrsReservoirLevelVolumeImpl implements JaxrsReservoirLevelVolume {
	@Autowired
	private ReservoirLevelVolumeRepos repository;

	@Override
	public JpaRepository<ReservoirLevelVolume, ReservoirLevelVolumeId> getRepository() {
		return repository;
	}

	@Override
	public List<ReservoirLevelVolume> findByReservoir(long reservoir) {
		return repository.findByIdReservoir(reservoir);
	}

	@Override
	public List<ReservoirLevelVolume> saveByReservoir(long reservoir, List<ReservoirLevelVolume> entities) {
		entities = entities.stream()
				.peek(x -> x.getId()
						.setReservoir(reservoir))
				.collect(Collectors.toList());
		return getRepository().save(entities);
	}

	@Override
	public void deleteByReservoir(long reservoir) {
		repository.deleteByReservoir(reservoir);
	}

	@Override
	public Option chart(long reservoir) {
		Option option = new Option();
		option.legend()
				.data("水位库容曲线");
		option.title()
				.show(false);

		Map<BigDecimal, Double> lvs = new TreeMap<>();
		repository.findByIdReservoir(reservoir)
				.forEach(lv -> lvs.put(lv.getId()
						.getWaterLevel(), lv.getVolume()));

		CategoryAxis xAxis = new CategoryAxis().show(true);
		xAxis.data()
				.addAll(lvs.keySet());
		option.xAxis(xAxis);

		option.yAxis(new ValueAxis().show(true));

		Line line = new Line();
		line.data()
				.addAll(lvs.values());
		option.series()
				.add(line);

		return option;
	}
}
